package com.ruoyi.web.controller.basedata;

import com.ruoyi.basedata.domain.Collector;
import com.ruoyi.basedata.domain.Concentrator;
import com.ruoyi.basedata.service.ICollectorService;
import com.ruoyi.basedata.service.IConcentratorService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/basedata/collector")
public class CollectorController extends BaseController {

    @Autowired
    private ICollectorService collectorService;
    @Autowired
    private IConcentratorService concentratorService;

    /**
     * 动态查询采集器列表
     * @param concentratorId
     * @param collectorName
     * @param collectorAdd
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:list')")
    @GetMapping("/list")
    public TableDataInfo list(@RequestParam(required = false) String concentratorAddress,
                              @RequestParam(required = false) Long concentratorId,
                              @RequestParam(required = false) String collectorName,
                              @RequestParam(required = false) String collectorAdd,
                              @RequestParam(required = false) Long[] concentratorIds,
                              @RequestParam(required = false) String concentratorName) {
        Collector collector = Collector.builder().concentratorId(concentratorId).concentratorAddress(concentratorAddress).collectorName(collectorName).collectorAdd(collectorAdd).concentratorName(concentratorName).build();
        startPage();
        List<Collector> collectorList = new ArrayList<>();
        if (concentratorIds == null){
            return getDataTable(collectorList);
        }
        collectorList = collectorService.getCollectorList(collector,concentratorIds);
        return getDataTable(collectorList);
    }

    /**
     * 查看采集器详情
     */
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id){
        return success(collectorService.getCollectorById(id));
    }

    /**
     * 新增采集器
     * @param collector
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:add')")
    @Log(title = "采集器管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult insert(@Validated @RequestBody Collector collector){
        Concentrator concentrator = concentratorService.selectConcentratorByID(collector.getConcentratorId());
        if (concentrator == null){
            return error("所选集中器不存在或已被删除！");
        }
        collector.setTenantId(concentrator.getTenantId());
        collector.setDelFlag(0);
        Boolean b = collectorService.insertCollector(collector);
        if (b){
            return success();
        }
        return error();
    }

    /**
     * 修改采集器
     * @param collector
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:edit')")
    @Log(title = "采集器管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Collector collector){
        Concentrator concentrator = concentratorService.selectConcentratorByID(collector.getConcentratorId());
        if (concentrator == null){
            return error("所选集中器不存在或已被删除！");
        }
        collector.setTenantId(concentrator.getTenantId());
        Boolean b = collectorService.updateCollector(collector);
        if (b){
            return success();
        }
        return error();
    }

    /**
     * 删除集中器
     * @param IDs
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:remove')")
    @Log(title = "采集器管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public AjaxResult del(@PathVariable Long IDs){
        Boolean b = collectorService.deleteCollector(IDs);
        if (b){
            return success();
        }
        return error();
    }

    @PreAuthorize("@ss.hasPermi('basedata:concentrator:export')")
    @Log(title = "采集器管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(required = false) String concentratorAddress,
                       @RequestParam(required = false) Long concentratorId,
                       @RequestParam(required = false) String collectorName,
                       @RequestParam(required = false) String collectorAdd,
                       @RequestParam(required = false) Long[] concentratorIds,
                       @RequestParam(required = false) String concentratorName) {
        Collector collector = Collector.builder().concentratorId(concentratorId).concentratorAddress(concentratorAddress).collectorName(collectorName).collectorAdd(collectorAdd).concentratorName(concentratorName).build();
        List<Collector> collectorList = new ArrayList<>();
        if (concentratorIds != null){
            collectorList = collectorService.getCollectorList(collector,concentratorIds);
        }
        ExcelUtil<Collector> util = new ExcelUtil<>(Collector.class);
        util.exportExcel(response, collectorList, "采集器管理数据");
    }

    /**
     * 根据concentratorId来查询集中器
     * @param concentratorId
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:list')")
    @GetMapping("/getCollectorByConcentratorId/{concentratorId}")
    public TableDataInfo getCollectorByConcentratorId(@PathVariable Long concentratorId){
        List<Collector> collectorByConcentratorId = collectorService.getCollectorByConcentratorId(concentratorId);
        return getDataTable(collectorByConcentratorId);
    }


    @PostMapping("/importData")
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:import')")
    public AjaxResult importData(MultipartFile file) {
        try {
            ExcelUtil<Collector> util = new ExcelUtil<>(Collector.class);
            List<Collector> list = util.importExcel(file.getInputStream());
            collectorService.importData(list);
            return success("导入成功");
        } catch (Exception e) {
            logger.error("导入失败", e);
            return error(e.getMessage());
        }
    }

    @PostMapping("/exportTemplate")
    @PreAuthorize("@ss.hasAnyPermi('basedata:collector:exportTemplate')")
    public void exportTemplate(HttpServletResponse response) {
        List<Collector> list = Collections.singletonList(new Collector());
        ExcelUtil<Collector> util = new ExcelUtil<>(Collector.class);
        util.hideColumn("concentratorName", "concentratorAddress");
        util.exportExcel(response, list, "采集器管理数据");
    }
}
